import {UserActions} from './user';
import {v4 as uuid} from 'uuid';

const initialState = {};

export const OrderMessageActions = {
  ORDER_MESSAGE_UPDATE: 'order_message_update',
  ORDER_MESSAGE_BATCH_UPDATE: 'order_message_batch_update',
  ORDER_MESSAGE_READ: 'order_message_read',
  ORDER_MESSAGE_RESET: 'order_message_reset',
};

export function readOrderMessage(payload) {
  return {
    type: OrderMessageActions.ORDER_MESSAGE_READ,
    payload,
  };
}

export function updateOrderMessage(payload) {
  return {
    type: OrderMessageActions.ORDER_MESSAGE_UPDATE,
    payload,
  };
}

export function batchUpdateOrderMessage(payload) {
  return {
    type: OrderMessageActions.ORDER_MESSAGE_BATCH_UPDATE,
    payload,
  };
}

export function resetOrderMessage() {
  return {
    type: OrderMessageActions.ORDER_MESSAGE_RESET,
  };
}

export default function orderMessageList(state = initialState, action) {
  switch (action.type) {
    case OrderMessageActions.ORDER_MESSAGE_UPDATE:
      return {
        ...state,
        [action.payload.id]: {
          ...action.payload,
        },
      };
    case OrderMessageActions.ORDER_MESSAGE_BATCH_UPDATE:
      action.payload.forEach(order => {
        state[order.id] = {
          ...order,
          messages: order.messages.map(msg => ({
            ...msg,
            uid: uuid(),
          })),
        };
      });
      return {...state};
    case OrderMessageActions.ORDER_MESSAGE_RESET:
      return {};
    case OrderMessageActions.ORDER_MESSAGE_READ:
      const order = state[action.payload];
      order.unread = 0;
      order.vendor_unread = 0;
      state[order.id] = order;
      return {...state};
    case UserActions.USER_SIGN_OUT:
      return {};
    default:
      return state;
  }
}
